package com.Jshop.gateway.filter;


import com.Jshop.common.utils.CookieUtils;
import com.Jshop.gateway.config.FilterProperties;
import com.Jshop.gateway.config.JwtProperties;
import com.Jshop.gateway.utils.JwtUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;

/**
 * 本拦截器用于jwt用于验证jwt有效性 放行后 在微服务中则是用于提取用户信息id name
 * */
@Component
@EnableConfigurationProperties({JwtProperties.class,FilterProperties.class})
public class LoginFilter extends ZuulFilter {

    @Resource
    private JwtProperties properties;


    private List<String> allowPaths;
    private static final Logger logger = LoggerFactory.getLogger(LoginFilter.class);


    public LoginFilter(FilterProperties filterProperties) {
        this.allowPaths = CollectionUtils.isEmpty(filterProperties.getAllowPaths()) ? Collections.emptyList() : filterProperties.getAllowPaths();
    }

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 5;
    }

    @Override
    public boolean shouldFilter() {
        //获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        //获取request
        HttpServletRequest request = ctx.getRequest();
        //获取请求路径
        String requestURL = request.getRequestURL().toString();

        //判断白名单
        for (String allowPath : allowPaths) {
            if (requestURL.contains(allowPath)) {
                //白名单放行 不需要登录校验
                return false;
            }
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //获取上下文
        RequestContext context = RequestContext.getCurrentContext();
        //获取request
        HttpServletRequest request = context.getRequest();
        //获取token
        String token = CookieUtils.getCookieValue(request, this.properties.getCookieName());
        //校验
        try {
            //通过，放行
            JwtUtils.getInfoFromToken(token,this.properties.getPublicKey());
        }catch (Exception e){
            //检验出现异常，返回403
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(HttpStatus.FORBIDDEN.value());
            logger.error("非法访问，未登录，地址：{}",request.getRemoteHost(),e);
        }
        return null;
    }
}
